package com.vit.mep;

import net.rim.device.api.system.Application;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.MenuItem;
import net.rim.device.api.ui.component.BasicEditField;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.EmailAddressEditField;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.component.NullField;
import net.rim.device.api.ui.component.RichTextField;
import IDTech.MSR.uniMag.uniMagReader;
import IDTech.MSR.uniMag.uniMagReaderMsg;

import com.vit.bb.VitScreen;
import com.vit.mep.model.TransactionData;

public class MepReaderScreen extends VitScreen implements uniMagReaderMsg,
		FieldChangeListener {
		
	protected MepApp _mepApp;

	private MenuItem mnItm_playing199 = new PowerUpUnimagReader();
	//private MenuItem mnItm_deleteLog = new DeleteLog();

	private uniMagReader _myUniMagReader = null;

	private String result;

	public LabelField _lblStatus;	
	public RichTextField _rtfInstruction;

	public LabelField lblF_Space;

	public ButtonField _btnSwipe;
	public ButtonField _btnCancel;	
	
	
	protected ButtonField _btnTest;
	
	
	public int _btnSwipeIndex = 0;

	
	protected EmailAddressEditField _txtEmail;
	protected BasicEditField _txtDui;
	protected BasicEditField _txtAmmount;
	
	
	
	
	protected static final String SWIPE_CARD = "Deslizar Tarjeta";//"Swipe Card";
	protected static final String REVIEW_CARD = "REVISAR";
	
	
	protected static final String FAIL ="Fail";
	protected static final String POWER_UP ="Power Up";
	protected static final String RETRIEVE ="Obtener Datos";
	protected static final String INSTRUCTIONS = "Deslice la tarjeta y presione \"Obtener Datos \" ";
	
	//TODO: para borrar el boton de pruebas poner en false
	private boolean _ISTEST = true;

	public MepReaderScreen(MepApp mepApp) {

		_mepApp = mepApp;
		
		InitializeReader();

		setTitle("MEP - Lectura Tarjeta");
		

	
		_lblStatus = new LabelField();
		_lblStatus.setText(MepReaderScreen.INSTRUCTIONS);		

		_btnSwipe = new ButtonField(MepReaderScreen.SWIPE_CARD, Field.FIELD_HCENTER
				| ButtonField.CONSUME_CLICK);
		_btnSwipe.setChangeListener(this);
				
		
		result = "";


		lblF_Space = new LabelField();
		lblF_Space.setText("      ");

		
		_vfManager.add(_btnSwipe);

		_vfManager.add(lblF_Space);
		
		
		_txtEmail = new EmailAddressEditField("email: ", "");				
		_txtAmmount  = new BasicEditField("Monto: " , "", 10, BasicEditField.FILTER_NUMERIC);
		_txtDui = new BasicEditField("DUI: ", "", 15, BasicEditField.FILTER_NUMERIC);

		
		
		_vfManager.add(_txtAmmount);
		_vfManager.add(_txtDui);
		_vfManager.add(_txtEmail);

		//TODO:borrar al finalizar las pruebas
		if(_ISTEST){
			_btnTest = new ButtonField("TEST", Field.FIELD_HCENTER | ButtonField.CONSUME_CLICK);
			_btnTest.setChangeListener(new TestBtnListener());		
			_vfManager.add(_btnTest);//*/	
		}
		

		_vfManager.add(new NullField(Field.FOCUSABLE));

		_btnSwipeIndex = _btnSwipe.getIndex();

		add(_vfManager);


		setStatus(_lblStatus);

		addMenuItem(mnItm_playing199);
		//addMenuItem(mnItm_deleteLog);

		addMenuItem(new MenuItem("Acerca de", 100, 100) {
			public void run() {
				//TODO: about screen
			}
		});

	}

	public boolean onClose() {
		if (_myUniMagReader != null)
			_myUniMagReader.closeReader();

		super.close();
		return true;
	}

	private void InitializeReader() {
		if (_myUniMagReader == null)
			_myUniMagReader = new uniMagReader(this);
	}

	void initializeSwipeScreen() {
		_rtfInstruction = new RichTextField(MepReaderScreen.POWER_UP,Field.NON_FOCUSABLE);		
		_btnCancel = new ButtonField("Cancel", ButtonField.CONSUME_CLICK);
		_btnCancel.setChangeListener(this);

	}

	public void fieldChanged(Field field, int context) {
		if (field == _btnCancel) {
			_btnCancel.getScreen().close();
		} else if (field == _btnSwipe) {
			if (_myUniMagReader != null) { // If Instruction Button is currently
											// disable, then skip the event

				String strStep = _btnSwipe.getLabel();

				if (strStep.equals(MepReaderScreen.SWIPE_CARD)) {
					

					result = "";
					_vfManager.delete(_btnSwipe);
					_vfManager.invalidate();

					_myUniMagReader.startSwipeCard();
				} else if (strStep.equals(MepReaderScreen.RETRIEVE)) {
					result = "";
					_vfManager.delete(_btnSwipe);
					_vfManager.invalidate();

					_myUniMagReader.retrieveCardData();
				} else {
				}
			}
		}

	}

	/*
	private class DeleteLog extends MenuItem {
		public DeleteLog() {
			super("Delete Logs", 00, 100);
		}

		public void run() {
			if (_myUniMagReader != null) {
				_myUniMagReader.deleteLogs();
			}

		}

	}//*/

	/*
	private class StartRecording extends MenuItem {
		public StartRecording() {
			super("Start recording", 0, 100);
		}

		public void run() {

			if (_myUniMagReader != null) {
				result = "";
				// //btn__instruction.setVisualState(VISUAL_STATE_DISABLED);
				_vfManager.delete(_btnSwipe);
				_vfManager.invalidate();

				_myUniMagReader.retrieveCardData();
			}

		}
	}//*/

	/*
	private class StopRecording extends MenuItem {
		public StopRecording() {
			super("Stop recording", 0, 100);
		}

		public void run() {

			if (_myUniMagReader != null) {
			}
			// _myUniMagReader.stopSwipeCard();

		}
	}//*/

	private class PowerUpUnimagReader extends MenuItem {
		public PowerUpUnimagReader() {
			super(MepReaderScreen.SWIPE_CARD, 0, 100);
		}

		public void run() {

			if (_myUniMagReader != null) {
				result = "";
				_vfManager.delete(_btnSwipe);
				_vfManager.invalidate();

				_myUniMagReader.startSwipeCard();
			}

		}
	}

	public void onReceiveMsgCardData(byte flagOfCardData, final byte[] res) {
		final String str_MSRData;

		byte flag = (byte) (flagOfCardData & 0x04);

		if (flag == 0x00)
			str_MSRData = new String(res);
		else if (flag == 0x04) {
			// You need to dencrypt the data here first.
			str_MSRData = new String(res);
		} else
			str_MSRData = null;

		StringBuffer hexString = new StringBuffer();
		hexString.append("<");
		String fix = null;
		for (int i = 0; i < res.length; i++) {
			fix = Integer.toHexString(0xFF & res[i]);
			if (fix.length() == 1)
				fix = "0" + fix;
			hexString.append(fix);
			if ((i + 1) % 4 == 0 && i != (res.length - 1))
				hexString.append(' ');
		}
		hexString.append("> ");

		final String str_RawHex = hexString.toString();

		_myUniMagReader.writeLogIntoFile("HexString is " + str_RawHex);

		Runnable msgRunnable;
		msgRunnable = new Runnable() {
			public void run() {
				if (str_MSRData.compareTo("FAIL") == 0) {
					_btnSwipe.setLabel(MepReaderScreen.SWIPE_CARD);
					_lblStatus
							.setText("Failed to read card, press \"Swipe Card \" button to retry");
				} else {
					_btnSwipe.setLabel(MepReaderScreen.SWIPE_CARD);
					_lblStatus.setText("Decoded Data is ");
				}

				result = str_MSRData;
				_lblStatus.setText("Ir a Confirmar Transaccion");
				
				
								
				//TODO:enviar a otra pantalla, para la confirmacion.				
				_vfManager.insert(_btnSwipe, _btnSwipeIndex);
				TransactionData td = getTransactionData();
				td.parseCardData();
				_mepApp.showConfirmationScreen(td);
			}
		};

		Application.getApplication().invokeLater(msgRunnable);

	}

	public void onReceiveMsgConnected() {

		_myUniMagReader.writeLogIntoFile("D,onReceiveMsgConnected");

		Runnable msgRunnable;

		msgRunnable = new Runnable() {
			public void run() {
				_btnSwipe.setLabel(MepReaderScreen.RETRIEVE);
				_vfManager.insert(_btnSwipe, _btnSwipeIndex);
				_lblStatus.setText(MepReaderScreen.INSTRUCTIONS);
			}
		};

		Application.getApplication().invokeLater(msgRunnable);

	}

	public void onReceiveMsgDisconnected() {
		_myUniMagReader.writeLogIntoFile("D,onReceiveMsgDisconnected");

		Runnable msgRunnable;

		msgRunnable = new Runnable() {
			public void run() {
				_lblStatus.setText("Please Plugin Card Reader");
				_btnSwipe.setLabel(MepReaderScreen.SWIPE_CARD);
				_vfManager.insert(_btnSwipe, _btnSwipeIndex);

			}
		};

		Application.getApplication().invokeLater(msgRunnable);

	}

	public void onReceiveMsgTimeout(String strTimeoutMsg) {
		_myUniMagReader.writeLogIntoFile("D,onReceiveMsgTimeout:"
				+ strTimeoutMsg);

		Runnable msgRunnable;

		msgRunnable = new Runnable() {
			public void run() {
				_btnSwipe.setLabel(MepReaderScreen.SWIPE_CARD);
				_vfManager.insert(_btnSwipe, _btnSwipeIndex);
				//_lblStatus.setText("Read card failed! Press \"Swipe Card \" button to try again");
				_lblStatus.setText("Lectura Fallida! Intente de nuevo");
				result = "";
			}
		};

		Application.getApplication().invokeLater(msgRunnable);

	}

	public void onReceiveMsgFail(int index, String strFailMsg) {
		Runnable msgRunnable;
		final String str_failMsg;

		if (strFailMsg.toUpperCase().startsWith(MepReaderScreen.FAIL))
			str_failMsg = new String(
					"Lectura Fallida! Intente de nuevo");
		else
			str_failMsg = "Err:" + index + "," + strFailMsg;

		msgRunnable = new Runnable() {
			public void run() {

				_btnSwipe.setLabel(MepReaderScreen.SWIPE_CARD);
				_vfManager.insert(_btnSwipe, _btnSwipeIndex);
				_lblStatus.setText(str_failMsg);
				result = "";
			}
		};

		Application.getApplication().invokeLater(msgRunnable);
	}
	
	
	public TransactionData getTransactionData(){
		TransactionData data = new TransactionData();
		data.setMonto(_txtAmmount.getText());
		data.setDui(_txtDui.getText());
		data.setEmail(_txtEmail.getText());
		data.setCardData(result);
		return data;
	}
	

	public void onReceiveMsgToConnect() {

	}

	public void onReceiveMsgToSwipeCard() {

	}

	public void onReceiveStatusMsg(int index, final String strMsg) {

		Runnable msgRunnable;

		msgRunnable = new Runnable() {
			public void run() {
				_lblStatus.setText(strMsg);
			}
		};

		Application.getApplication().invokeLater(msgRunnable);

	}
	
	
	
class TestBtnListener implements FieldChangeListener{		
		public void fieldChanged(Field field, int context) {
			//result = "%B1234123412341234^CardUser/John^030510100000019301000000877000000?";
			//result = "%B4310634000101876^CARLOS RODRIGUEZ^1310101000000000000000407110000?;43106340000101876=13101010000040711000?";
			result = "%B4310640000174094^CARLOS/ RODRIGUEZ^13011011261700653000000?;4310640000174094=130110112617653?;?";
			TransactionData td  =  getTransactionData();
			td.parseCardData();
			_mepApp.showConfirmationScreen(td);
			
		}		
	}//TestBtnListener
	

}//class
